#!/usr/bin/python

import httplib2
import datetime 
import oauth2 as oauth
from xml.dom import minidom
import urllib
import time

class MDelicious:
    def __init__(self, username, password):
        self.username = username
        self.password = password
        
    def posts_all(self, tag=None, start_date=None, end_date=None):
        base_url = 'https://api.del.icio.us/v1/posts/all?'
        params = {}
        if tag: params["tag"] = tag
        if start_date: params["fromdt"] = start_date.strftime("%Y-%m-%dT%H:%M:%SZ") 
        if end_date: params["todt"] = end_date.strftime("%Y-%m-%dT%H:%M:%SZ") 

        url = base_url + urllib.urlencode(params)

        http = httplib2.Http()
        http.add_credentials(self.username, self.password)
        response, content = http.request(url)
        return self.process_response(content)
        
    def process_response(self, content):
        dom = minidom.parseString(content)
        posts = []

        for node in dom.getElementsByTagName('post'):
            posts.append({
                'href': node.getAttribute('href'),
                'hash': node.getAttribute('hash'),
                'description': node.getAttribute('description'),
                'time': datetime.datetime.strptime(
                    node.getAttribute('time'), "%Y-%m-%dT%H:%M:%SZ"),
                'extended': node.getAttribute('extended'),
                'meta': node.getAttribute('meta'),
                'tags':  node.getAttribute('tag').split(" "),
            })
        return posts
        
class MDeliciousOAuth(MDelicious):
    def __init__(self, delicious_login_oauth):
        self.delicious_login_oauth = delicious_login_oauth
        
    def posts_all(self, tag=None, start_date=None, end_date=None):
        
        consumer = oauth.Consumer(
            self.delicious_login_oauth.consumer_key, 
            self.delicious_login_oauth.consumer_secret) 

        token2 = oauth.Token(self.delicious_login_oauth.oauth_token, 
            self.delicious_login_oauth.oauth_token_secret)
        
        params = {
            'oauth_version': "1.0",
            'oauth_nonce': oauth.generate_nonce(),
            'oauth_timestamp': int(time.time())
        }

        params['oauth_token'] = self.delicious_login_oauth.oauth_token
        params['oauth_consumer_key'] = self.delicious_login_oauth.consumer_key

        if tag: params["tag"] = tag
        if start_date: params["fromdt"] = start_date.strftime("%Y-%m-%dT%H:%M:%SZ") 
        if end_date: params["todt"] = end_date.strftime("%Y-%m-%dT%H:%M:%SZ") 
    
        req = oauth.Request(method="GET", url="http://api.del.icio.us/v2/posts/all", parameters=params)
        signature_method = oauth.SignatureMethod_HMAC_SHA1()
        req.sign_request(signature_method, consumer, token2)
    
        base_url = 'http://api.del.icio.us/v2/posts/all?'
        

        url = req.to_url()

        http = httplib2.Http()

        response, content = http.request(url)

        return self.process_response(content)
